package com.atguigu.lease.web.admin.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.在请求头中，获取token
        //如果按照_写，记得swagger里改成-
        String accessToken = request.getHeader("access-token");
        if(!StringUtils.hasLength(accessToken)){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else{
            //解析token token一旦过期或被篡改了。会抛对应的异常
            Claims claims = JwtUtil.parseToken(accessToken);
            //获取用户的id
            Long userId = claims.get("userId", Long.class);
            //获取用户名
            String username = claims.get("username", String.class);
            //创建一个Loginuser对象，只存储userId，和username
            LoginUser loginUser = new LoginUser(userId,username);
            //为了在整个项目中当前线程可以在任一环节取出LoginUser，加了个ThreadLocal
            LoginUserContext.setLoginUser(loginUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        LoginUserContext.removeLoginUser();
    }
}
